<?php
define('type_max_point', "maxPoint");


function set_point_by_fromUserName($fromUserName,$type,$onlyOne=NULL,$detail='',$materialId=NULL,$eventId=NULL,$resPoint=0,$judgemaxPoint=true){
	$cid = Session::$user['customerId'];
	
	if($resPoint != 0){
		$handleOver = handleUserPoint($type,$fromUserName,$resPoint,$detail,NULL,$materialId,$judgemaxPoint);
		return $handleOver;
	}
	
	//判断积分表是否存在
	$CustomerModule = new Model();
	$dbName = C('DB_NAME');
	// 	$pointsModuleSql = 'SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = "weixin" AND table_name = "wx_'.$cid.'_module_set_points"';
	$pointsModuleSql = 'SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = "'.$dbName.'" AND table_name = "wx_'.$cid.'_module_set_points"';
	
	$pointsResult = $CustomerModule->query($pointsModuleSql);
	
	$SetPoints = null;
	if($pointsResult[0]["count"] >0 ){
		$SetPoints = D("module_set_points");
	}else{
		return false;
	}
	$condition['pointType'] = $type;
	$setPoint = $SetPoints->where($condition)->select();
	if($setPoint){
		$point = (int)$setPoint[0]['points'];
		if($point != 0){
			Session::switchCustomer(0);
			$PointsModel = D("user_interact_points_detail");
			Session::switchCustomer($cid);
				
			if($onlyOne){
				$pc['source'] = $type;
				$pc['fromUserName'] = $fromUserName;
				$pc['customerId'] = $cid;
				if($materialId != NULL){
					$pc['materialId'] = $materialId;
				}
				$onlyPoints = $PointsModel->where($pc)->find();
	
				if($onlyPoints){
					Log::write($type.' has add points!');
					return false;
				}
	
			}
			$condition['pointType'] = module_handle_maxPoint;
			$maxPoint = $SetPoints->where($condition)->find();
			if($maxPoint && $maxPoint['points']>0){
				$handleOver = handleUserPoint($type,$fromUserName,$point,$detail,$maxPoint['points'],$materialId,$judgemaxPoint);
			}else{
				$handleOver = handleUserPoint($type,$fromUserName,$point,$detail,NULL,$materialId,$judgemaxPoint);
			}
			return $handleOver;
		}
	}
}


/**
 * 活动积分
 * @param  $type moduleName or text 
 * @param  $fromUserName
 * @param  $onlyOne 是否只加一次积分
 * @param  $materialId 插件素材ID
 * @param  $eventId 活动id
 * @param  $judgemaxPoint 判断获取积分 是否受上限影响
 */
function set_point_by_point_type($type, $fromUserName,$onlyOne=NULL,$detail='',$materialId=NULL,$eventId=NULL,$resPoint=0,$judgemaxPoint=true) {
	
	$result = set_point_by_fromUserName($fromUserName,$type,$onlyOne,$detail,$materialId,$eventId,$resPoint,$judgemaxPoint);
	return $result;
}


/*
 * 处理user表中消息相关用户信息,判断存在以及更新
*/
function handleUserPoint($pointType,$fromUserName,$point,$detail,$maxPoint=NULL,$materialId=NULL,$eventId=NULL,$judgemaxPoint=true){
	
	if($point > 0){
		if($judgemaxPoint){
			if($maxPoint != NULL){
				$todayPoint = get_today_point($fromUserName);
				if($todayPoint >=$maxPoint ){
					return false;
				}
				else if($todayPoint +$point >$maxPoint){//超过上限截断
					$point = $maxPoint-$todayPoint;
				}
			}
		}
	}
	
	$cid = Session::$user['customerId'];
	Session::switchCustomer(0);
	$UserInteractPointDetailModel = M("user_interact_points_detail");
// 	$UserPointAndStoredValueTotalModel = M("user_point_and_stored_value_total");
	$UserInteractTotalModel = M("user_interact_point_total");
	Session::switchCustomer($cid);
	
	$time = date("Y-m-d H:i:s");
	$UserInteractPointDetailModel->create();
	$UserInteractPointDetailModel->fromUserName = $fromUserName;
	$UserInteractPointDetailModel->customerId = $cid;
	$UserInteractPointDetailModel->source = $pointType;
	$UserInteractPointDetailModel->sourceDetail = $detail;
	$UserInteractPointDetailModel->points = (int)$point;
	$UserInteractPointDetailModel->createTime = $time;
	$UserInteractPointDetailModel->materialId = $materialId;
	$UserInteractPointDetailModel->eventId = $eventId;
	$UserInteractPointDetailModel->add();
	
	$totalCondition['customerId'] =array('eq',$cid);
	$totalCondition['fromUserName'] =array('eq',$fromUserName);
	$userTotal = $UserInteractTotalModel->where($totalCondition)->find();
	if (isset($userTotal)) {
		$data['updateTime'] = $time;
		$data['interactScore'] = $point +(int)$userTotal['interactScore'];
	
		$saveOk = $UserInteractTotalModel->where($totalCondition)->save($data);
		if($saveOk){
			return true;
		}
	} else {
		$UserInteractTotalModel->create();
		$data['customerId'] = $cid;
		$data['fromUserName'] = $fromUserName;
		$data['updateTime'] = $time;
		$data['interactScore'] = $point;
		$updatOk = $UserInteractTotalModel->add($data);
		if($updatOk != false){
			return true;
		}
	}
	
	return false;
}

/**
 * 互动积分保存
 * @param unknown $fromUserName
 * @param unknown $pointType
 * @param unknown $points
 * @param string $materialId
 * @param string $eventId
 */
// function savePointInfo($uniUserId,$pointType,$points,$detail=NULL,$materialId=NULL,$eventId=NULL){
// 	$cid = Session::$user['customerId'];
// 	Session::switchCustomer(0);
// 	$UserInteractPointDetailModel = M("user_interact_points_detail");
// 	$UserPointAndStoredValueTotalModel = M("user_point_and_stored_value_total");
// 	Session::switchCustomer($cid);
	
// 	$time = date("Y-m-d H:i:s");
// 	$UserInteractPointDetailModel->create();
// 	$UserInteractPointDetailModel->uniUserId = $uniUserId;
// 	$UserInteractPointDetailModel->customerId = $cid;
// 	$UserInteractPointDetailModel->source = $pointType;
// 	$UserInteractPointDetailModel->sourceDetail = $detail;
// 	$UserInteractPointDetailModel->points = (int)$points;
// 	$UserInteractPointDetailModel->createTime = $time;
// 	$UserInteractPointDetailModel->materialId = $materialId;
// 	$UserInteractPointDetailModel->eventId = $eventId;
// 	$UserInteractPointDetailModel->add();

// 	$totalCondition['customerId'] =array('eq',$cid);
// 	$totalCondition['uniUserId'] =array('eq',$uniUserId);
// 	$userTotal = $UserPointAndStoredValueTotalModel->where($totalCondition)->find();
// 	if (isset($userTotal)) {
// 		$data['updateTime'] = $time;
// 		$data['interactScore'] = $points +(int)$userTotal['interactScore'];
	
// 		$saveOk = $UserPointAndStoredValueTotalModel->where($totalCondition)->save($data);
// 		if($saveOk){
// 			return true;
// 		}
// 	} else {
// 		$UserPointAndStoredValueTotalModel->create();
// 		$data['customerId'] = $cid;
// 		$data['uniUserId'] = $uniUserId;
// 		$data['updateTime'] = $time;
// 		$data['interactScore'] = $points;
// 		$data['consumeScore'] = 0;
// 		$data['storedValue'] = 0;
// 		$updatOk = $UserPointAndStoredValueTotalModel->add($data);
// 		if($updatOk != false){
// 			return true;
// 		}
// 	}
	
// 	return false;
// }


/**
 * 保存消费积分
 * @param unknown $fromUserName
 * @param unknown $pointType
 * @param unknown $points
 * @param string $materialId
 * @param string $eventId
 * @return boolean
 */
function saveConsumePointInfo($fromUserName,$pointType,$points,$detail=NULL,$materialId=NULL,$eventId=NULL){
	$cid = Session::$user['customerId'];
	Session::switchCustomer(0);
	$UserConsumePointDetailModel = M("user_consume_points_detail");
// 	$UserPointAndStoredValueTotalModel = M("user_point_and_stored_value_total");
	$UserConsumeTotalModel = M("user_consume_point_total");
	Session::switchCustomer($cid);
	
	$time = date("Y-m-d H:i:s");
	$UserConsumePointDetailModel->create();
	$UserConsumePointDetailModel->fromUserName = $fromUserName;
	$UserConsumePointDetailModel->customerId = $cid;
	$UserConsumePointDetailModel->source = $pointType;
	$UserConsumePointDetailModel->sourceDetail = $detail;
	$UserConsumePointDetailModel->points = (int)$points;
	$UserConsumePointDetailModel->createTime = $time;
	$UserConsumePointDetailModel->materialId = $materialId;
	$UserConsumePointDetailModel->eventId = $eventId;
	$UserConsumePointDetailModel->add();

	
	$totalCondition['customerId'] =array('eq',$cid);
	$totalCondition['fromUserName'] =array('eq',$fromUserName);
	$userTotal = $UserConsumeTotalModel->where($totalCondition)->find();
	if (isset($userTotal)) {
		$data['updateTime'] = $time;
		$data['consumeScore'] = $points +(int)$userTotal['consumeScore'];
	
		$saveOk = $UserConsumeTotalModel->where($totalCondition)->save($data);
		if($saveOk){
			return true;
		}
	} else {
		$UserConsumeTotalModel->create();
		$data['customerId'] = $cid;
		$data['fromUserName'] = $fromUserName;
		$data['updateTime'] = $time;
		$data['consumeScore'] = $points;
		$updatOk = $UserConsumeTotalModel->add($data);
		if($updatOk != false){
			return true;
		}
	}
	
	return false;
}

/**
 * 互动积分今天目前积分数
 * @param unknown $fromUserName
 * @return number
 */
function get_today_point($fromUserName){
	$cid = Session::$user['customerId'];
	Session::switchCustomer(0);
	$UserInteractDetailModel = D('user_interact_points_detail');
	Session::switchCustomer($cid);
	
	$startDate =  date('Y-m-d H:i:s',strtotime(date('Y-m-d')));
	$endDate =  date('Y-m-d H:i:s',strtotime(date('Y-m-d'))+24*3600);
	$condition['fromUserName'] = array('eq',$fromUserName);
	$condition['customerId'] = array('eq',$cid);
	$condition['createTime'] = array('between',array($startDate,$endDate));
	
	$interactPoint = $UserInteractDetailModel->where($condition)->sum('points');
	
	return (int)$interactPoint;
}
